<?php

namespace app\adminapi\logic\system;

use adminmatrix\admin\logic\BaseLogic;
use app\adminapi\model\Admin\AdminRole;
use adminmatrix\admin\annotation\Inject;
use app\Request;
use think\exception\HttpException;

use think\facade\Db;
class AdminRoleLogic extends BaseLogic
{
    #[Inject]
    protected AdminRole $model;


    public function setAuth(Request $request) :bool
    {
        Db::startTrans();
        try {
            $id     = $request->put("id");
            $role   =   $request->put('role');
            $data = $this->model->with(['perms'])->where('id' , $id)->findOrEmpty();
            if ($data->isEmpty()) throw new HttpException(200 , '角色不存在');

            $roleAll = [];
            foreach ($role as $roleId)
            {
                $roleAll[]   = [
                    'permission_id'   =>  $roleId,
                    'role_id'           => $id
                ];
            }


            # 先移除旧的权限
            $data->perms()->where('role_id' , $id)->delete();
            $data->perms()  ->saveAll($roleAll);
            # 更新权限
            // 提交事务
            Db::commit();

            return true;
        } catch (\Exception $e)
        {
            // 回滚事务
            Db::rollback();
            throw new HttpException($e->getCode() , $e->getMessage());
        }


    }
}